//
//  MKSystemPhotoLayout.swift
//  MKImageBrowser3
//
//  Created by 劢克科技 on 2019/5/13.
//  Copyright © 2019 meckey. All rights reserved.
//
//  预览的Collection Flow Layout

import UIKit

class MKSystemPhotoLayout: UICollectionViewFlowLayout {
    let distanceBetweenPages: CGFloat = 20
    
    override func prepare() {
        super.prepare()
        
        itemSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard var halfWidth = collectionView?.bounds.width else { return nil }
        halfWidth = halfWidth / 2
        let centerX = collectionView!.contentOffset.x + halfWidth
        var attributeArray = [UICollectionViewLayoutAttributes]()
        for i in 0..<collectionView!.numberOfItems(inSection: 0) {
            let indexPath = IndexPath(item: i, section: 0)
            guard let attribute = collectionView?.layoutAttributesForItem(at: indexPath) else { continue }
            attribute.center = CGPoint(x: attribute.center.x + (attribute.center.x - centerX) / halfWidth * distanceBetweenPages / 2, y: attribute.center.y)
            attributeArray.append(attribute)
        }
        return attributeArray
    }
}
